package com.voicenews;

import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gcm.GCMBaseIntentService;
import com.voicenews.R;
import com.voicenews.gcm.ReceivedArticlesListShowsActivity;
import com.voicenews.webserviceconnect.ICallbackHandler;
import com.voicenews.webserviceconnect.WebServiceConnector;

public class GCMIntentService extends GCMBaseIntentService implements
		ICallbackHandler {

	private static final String PROJECT_ID = "1024314874380";

	private static final String TAG = "GCMIntentService voicenews";

	public GCMIntentService() {
		super(PROJECT_ID);
		Log.d(TAG, "GCMIntentService init");
	}

	@Override
	protected void onError(Context ctx, String sError) {
		// TODO Auto-generated method stub
		Log.d(TAG, "Error: " + sError);

	}

	@Override
	protected void onMessage(Context ctx, Intent intent) {

		Log.d(TAG, "Message Received");
		String message = intent.getStringExtra("message");

		sendGCMIntent(ctx, message);
		generateNotification(ctx, message);

	}

	private void sendGCMIntent(Context ctx, String message) {

		Intent broadcastIntent = new Intent();
		broadcastIntent.setAction("GCM_RECEIVED_ACTION");

		broadcastIntent.putExtra("gcm", message);

		ctx.sendBroadcast(broadcastIntent);

	}

	@Override
	protected void onRegistered(Context ctx, String regId) {
		// TODO Auto-generated method stub
		// send regId to your server
		Log.d(TAG, regId);
		sendRegistrationIdToServer(regId);
	}

	@Override
	protected void onUnregistered(Context ctx, String regId) {
		// TODO Auto-generated method stub
		// send notification to your server to remove that regId

	}

	/**
	 * Issues a notification to inform the user that server has sent a message.
	 */
	private static void generateNotification(Context context, String message) {
		JSONObject jsonObject;
		try {
			// jsonObject = new JSONObject(message);
			// String content = jsonObject.getString("title");
			// String url = jsonObject.getString("url");
			int icon = R.drawable.tin_tong_hop_logo;
			long when = System.currentTimeMillis() - 5;
			String title = context.getString(R.string.app_name);
			NotificationManager notificationManager = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);
			// Notification notification = new Notification(icon, message,
			// when);

			
			System.out.println("article" + message);
//			String url = messageJson.optString("url");
//			String messageTitle = messageJson.optString("title");
			Intent notificationIntent = new Intent(context,
					ReceivedArticlesListShowsActivity.class);
			notificationIntent.putExtra("articlesJson", message);
//			// set intent so it does not start a new activity
//			notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
//					| Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
			notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//	        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

			PendingIntent intent = PendingIntent.getActivity(context, (int) when,
					notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

//			Notification notification = new Notification.Builder(context)
//					.setContentText(message).setContentTitle(title)
//					.setWhen(when).setSmallIcon(icon).build();

			String messageTitle = "có tin mới gửi từ " + title;
			Notification notification = new Notification(icon, messageTitle, when);

			notification.setLatestEventInfo(context, title, messageTitle, intent);
			notification.flags |= Notification.FLAG_AUTO_CANCEL;

			// Play default notification sound
			notification.defaults |= Notification.DEFAULT_SOUND;

			// // Vibrate if vibrate is enabled
			// notification.defaults |= Notification.DEFAULT_VIBRATE;
			notificationManager.notify((int) when, notification);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void sendRegistrationIdToServer(String idGCM) {
		SharedPreferences setting = getSharedPreferences(
				VoiceNewsApplication.filePrefrences, MODE_PRIVATE);
		String idClient = setting.getString("id", "noid");
		Map<String, String> params = new HashMap<String, String>();
		params.put("idClient", idClient);
		params.put("idGCM", idGCM);
		callWebService(params);

	}

	private void callWebService(Map<String, String> params) {
		WebServiceConnector webServiceConnector = new WebServiceConnector(
				VoiceNewsApplication.hostService + "rest/services/",
				"sendregistrationtoServer", params, this,
				WebServiceConnector.GET_METHOD, null);
		webServiceConnector.execute();
	}

	@Override
	public void response(String response) {
		// TODO Auto-generated method stub
		System.out.println("response from server : " + response);
		SharedPreferences settings = getSharedPreferences(
				VoiceNewsApplication.filePrefrences, MODE_PRIVATE);
		Editor editor = settings.edit();
		
		Context context = getApplicationContext();
		Intent registrationGCMSuccessfull = new Intent("responseFromGCMServer");

		if (response.equals("true")) {
			Toast.makeText(this, "success", Toast.LENGTH_SHORT);
			editor.putBoolean("registrationGCM", true);
			registrationGCMSuccessfull.putExtra("flag", true);
		} else {
			Toast.makeText(this, "fail", Toast.LENGTH_SHORT);
			editor.putBoolean("registrationGCM", true);
			registrationGCMSuccessfull.putExtra("flag", false);
		}
		editor.commit();
		context.sendBroadcast(new Intent(registrationGCMSuccessfull));
	}

}
